<?php
// +----------------------------------------------------------------------
// | Name: 咪乐多管理系统 [ 为了快速搭建软件应用而生的，希望能够帮助到大家提高开发效率。 ]
// +----------------------------------------------------------------------
// | Copyright: (c) 2020~2021 https://www.lvacms.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed: 这是一个自由软件，允许对程序代码进行修改，但希望您留下原有的注释。
// +----------------------------------------------------------------------
// | Author: 西安咪乐多软件 <997786358@qq.com>
// +----------------------------------------------------------------------
// | Version: V1
// +----------------------------------------------------------------------

/**
 * @Name 图片管理服务
 * @Description
 * @Auther 西安咪乐多软件
 * @Date 2021/11/23 21:12
 */

namespace Modules\Admin\Services\Image;


use Modules\Admin\Models\AdminImage;
use Modules\Admin\Services\Auth\TokenServices;
use Modules\Admin\Services\BaseApiServices;
use Modules\Admin\Services\Config\ConfigServices;
use Modules\Common\Lib\Oss\OssIndex;
use Modules\Common\Lib\Qiniu\QiniuIndex;

class ImageServices extends BaseApiServices
{
    public function upload(object $request)
    {
        if ($request->isMethod('POST')){
            $fileCharater = $request->file('file');
            if ($fileCharater->isValid()){
                $imageStatus = ConfigServices::getCodeValue('SiteConfiguration')['image_status'];
                $url = '';
                if($imageStatus == 1){
                    $path = $request->file('file')->store(date('Ymd'),'public');
                    if ($path){
                        $url = '/storage/upload/'.$path;
                    }
                }else if($imageStatus == 2){
                    $url = QiniuIndex::upload($fileCharater);
                }else if($imageStatus == 3){
                    $url = OssIndex::upload($fileCharater);
                }
                if ($url){
                    $userInfo = TokenServices::my();
                    $imageId = AdminImage::insertGetId([
                        'url'=>$url,
                        'open'=>$imageStatus,
                        'admin_id'=>$userInfo->id,
                        'status'=>0,
                        'created_at'=> date('Y-m-d H:i:s')
                    ]);
                    $url =  self::getHttp($imageStatus).$url;
                    return $this->apiSuccess('上传成功！',
                        [
                            'image_id'=>$imageId,
                            'url'=>$url
                        ]);
                }
            }
        }
        $this->apiError('上传失败');
    }


    public function getImageList(array $data){
        $userInfo = TokenServices::my();
        $list = AdminImage::query()->where('admin_id',$userInfo->id)->orderBy('id','desc')
            ->paginate($data['limit'])->toArray();
        return $this->apiSuccess('',[
           "list"=>$list['data'],
           "total"=>$list['total']
        ]);
    }
}
